<?php

namespace App\Http\Middleware;

use App\Handler\CompanyHandler;
use App\Kids\Caches\PrivilegeCacher;
use App\Models\ActionLog;
use App\Models\AdminActionLog;
use App\Models\Privilege;
use p5\objects\TimeUtils;
use Closure;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LogMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param  string|null $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
//        $args = $request->all();
//        $string = json_encode($args);
//        if (strlen($string) > 5000) {
//            $string = substr($string, 0, 5000);
//        }
//        $staffId = $this->first($request, ["login_staff_id", "login_admin_id"]);
//        if (empty($staffId)) {
//            return $next($request);
//        }
//        $staffName = $this->first($request, ["login_user_name", "login_staff_name"]);
//        $uri = $request->getUri();
//        $matrix = explode("/", $uri);
//        $size = count($matrix);
//        $matrix[$size - 1] = ($matrix[$size - 1] == "view") ? "detail" : $matrix[$size - 1];
//        $pid = $matrix[$size - 2] . "." . $matrix[$size - 1];
//
//        if ($this->isIgnoreAction($pid)) {
//            return $next($request);
//        }
//
//        $privilege = PrivilegeCacher::findPrivilege($pid);
//        $companyId = $request->get("login_company_id");
//        if (empty($privilege)) {
//            $systemFlag = (!empty($companyId) && $companyId * 1 > 0) ? "company" : "admin";
//            $privilege = $this->add_privilege($pid, $systemFlag);
//        }
//        if ($privilege["public_flag"] == 1) {
//            return $next($request);
//        }
//
//        $bean = new ActionLog();
//        $bean->set_action_id($pid);
//        $bean->set_staff_id($staffId);
//        $bean->set_user_name($staffName);
//        $bean->set_action_name($privilege["privilege_name"]);
//        $bean->set_action_ip($request->getClientIp());
//        $bean->set_created_at(TimeUtils::current_datetime());
//        $bean->set_params($string);
//
//        if (!empty($companyId) && $companyId > 0) {
//            $db = CompanyHandler::getDs($companyId);
//            $bean->set_staff_id($staffId);
//            $bean->setConnection($db)->save();
//        } else {
//            $log = new AdminActionLog();
//            $log->forceFill($bean->toArray());
//            $log->set_admin_id($staffId);
//            $log->save();
//        }

        return $next($request);
    }

    static private $ignoreGroups = ["timer", "helper"];
    static private $ignoreActions = ["staff.changeBranch", "dic.all"];
    static private $ignoreMethods = ["detail"];

    private function isIgnoreAction($uri)
    {
        if (in_array($uri, self::$ignoreActions)) {
            return true;
        }
        $matrix = explode(".", $uri);
        $module = $matrix[0];
        if (in_array($module, self::$ignoreGroups)) {
            return true;
        }
        $size = count($matrix);
        if ($size > 1 && in_array($matrix[$size - 1], self::$ignoreMethods)) {
            return true;
        }
        return false;
    }

    /**
     * @param string $privilegeId
     * @param string $systemFlag
     * @return Privilege|void
     */
    private function add_privilege($privilegeId, $systemFlag = "company")
    {
        $matrix = explode(".", $privilegeId);
        $size = count($matrix);
        $group = $matrix[$size - 1];
        $bean = new Privilege();
        $bean->set_group_name($group);
        $bean->set_privilege_id($privilegeId);
        $bean->set_privilege_name($privilegeId);
        $bean->set_public_flag(0);
        $bean->set_system_flag($systemFlag);
        $bean->set_order_number(120);
        PrivilegeCacher::addRecord($bean);
        try {
            $bean->save();
            return $bean;
        } catch (\Exception $e) {
            Log::error("保存权限记录出错");
            Log::error(json_encode($bean));
            Log::error($e->getTraceAsString());
        }
    }

    /**
     * @param $request \Illuminate\Http\Request $request
     * @param array $names
     * @return string
     */
    private function first($request, $names = [])
    {
        foreach ($names as $name) {
            if ($request->has($name)) {
                return $request->get($name);
            }
            return "";
        }
    }
}
